package com.recipedb.recipedb.security;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import java.util.Date;
import java.security.Key;

public class JwtUtil {
    // 临时固定 token 配置
    private static final String FIXED_TOKEN = "fixed-test-token-12345";
    private static final String FIXED_USERNAME = "root";
    private static final boolean USE_FIXED_TOKEN = false; // 设为 false 恢复真实 JWT

    private static final Key key = Keys.hmacShaKeyFor("your-32+chars-secret-key-goes-here!".getBytes());
    private static final long EXPIRATION_TIME = 1000L * 60 * 60 * 24; // 24小时

    public static String generateToken(String username) {
        if (USE_FIXED_TOKEN) {
            System.out.println("=== 使用固定 Token 进行测试 ===");
            System.out.println("请求用户名: " + username);
            System.out.println("返回固定 Token: " + FIXED_TOKEN);
            return FIXED_TOKEN;
        }

        // 真实 JWT 生成逻辑
        return Jwts.builder()
                .setSubject(username)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(key)
                .compact();
    }

    public static String validateToken(String token) {
        if (USE_FIXED_TOKEN) {
            System.out.println("=== 验证固定 Token ===");
            System.out.println("收到 Token: " + token);

            if (FIXED_TOKEN.equals(token)) {
                System.out.println("Token 验证成功，返回用户: " + FIXED_USERNAME);
                return FIXED_USERNAME;
            } else {
                System.out.println("Token 验证失败，期望: " + FIXED_TOKEN + "，实际: " + token);
                return null;
            }
        }

        // 真实 JWT 验证逻辑
        try {
            return Jwts.parserBuilder()
                    .setSigningKey(key)
                    .build()
                    .parseClaimsJws(token)
                    .getBody()
                    .getSubject();
        } catch (JwtException e) {
            return null;
        }
    }
}